import { useEffect, useRef, useState } from 'react'

export function useInfiniteScroll(options = {}) {
  const [isLoading, setIsLoading] = useState(false)
  const [hasMore, setHasMore] = useState(true)
  const observerTarget = useRef<HTMLDivElement>(null)
  const observer = useRef<IntersectionObserver | null>(null)

  const handleObserver = (entries: IntersectionObserverEntry[]) => {
    const [entry] = entries
    if (entry.isIntersecting && hasMore && !isLoading) {
      setIsLoading(true)
    }
  }

  useEffect(() => {
    if (observer.current) observer.current.disconnect()

    observer.current = new IntersectionObserver(handleObserver, {
      rootMargin: '200px', // 提前200px开始加载
      threshold: 0.1,
      ...options,
    })

    const target = observerTarget.current
    if (target) observer.current.observe(target)

    return () => {
      if (observer.current) observer.current.disconnect()
    }
  }, [hasMore, isLoading, options])

  const finishLoading = (newHasMore: boolean) => {
    setIsLoading(false)
    setHasMore(newHasMore)
  }

  return { observerTarget, isLoading, hasMore, finishLoading }
}